package com.yang.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import com.mysql.jdbc.StringUtils;
import com.yang.entity.Role;
/**
 * 处理角色列表
 * 
 * 该demo对于T的处理还有一些问题
 * 
 * eg: List<Role> <----> a,b
 * @author yang
 * @param <T>
 *
 */
public class RoleToStringTypeHandler<T> extends BaseTypeHandler<List<T>> {


	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType)
			throws SQLException {
		String temp = "";
		if(parameter.get(0) != null && parameter.get(0).getClass().getName().equals("Role.class")){
			for(T t : parameter){
				temp += ((Role) t).getName()+",";
			}
			if(!StringUtils.isEmptyOrWhitespaceOnly(temp)){
				temp = temp.substring(0,temp.length()-1);
			}
			ps.setString(i, temp);
		}else{
			ps.setObject(i, parameter+"");
		}
		
	}

	@Override
	public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String temp = rs.getString(columnName);
		if(temp != null){
			String[] data = temp.split(",");
			List<Role> list = new ArrayList<Role>(data.length);
			for(String r : data){
				list.add(new Role(r));
			}
			return (List<T>) list;
		}
		return null;
	}

	@Override
	public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String temp = rs.getString(columnIndex);
		if(temp != null){
			String[] data = temp.split(",");
			List<Role> list = new ArrayList<Role>(data.length);
			for(String r : data){
				list.add(new Role(r));
			}
			return (List<T>) list;
		}
		return null;
	}

	@Override
	public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String temp = cs.getString(columnIndex);
		if(temp != null){
			String[] data = temp.split(",");
			List<Role> list = new ArrayList<Role>(data.length);
			for(String r : data){
				list.add(new Role(r));
			}
			return (List<T>) list;
		}
		return null;
	}


}
